package com.ntt.benew.dictionary.view

import android.content.Context
import android.text.SpannableStringBuilder
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import androidx.constraintlayout.widget.ConstraintLayout
import com.benew.ntt.player.AudioItem
import com.benew.ntt.player.NttPlayCtrl
import com.benew.ntt.ydeval.listener.IEvalListener
import com.benew.ntt.ydeval.view.EvalEntity
import com.benew.ntt.ydeval.view.EvalManager
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.SizeUtils
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.reflect.TypeToken
import com.ntt.benew.dictionary.NttDictionaryManager
import com.ntt.benew.dictionary.R
import com.ntt.benew.dictionary.api.BenewApiManager
import com.ntt.benew.dictionary.constants.LangType
import com.ntt.benew.dictionary.databinding.DictSplitWordViewBinding
import com.ntt.benew.dictionary.entity.gpt.BaseEntity
import com.ntt.benew.dictionary.entity.gpt.ChunkingEntity
import com.ntt.benew.dictionary.entity.gpt.StructureEntity
import com.ntt.benew.dictionary.listener.IAnalysisListener
import com.ntt.benew.dictionary.listener.IClickPlayerListener
import com.ntt.benew.dictionary.listener.ITranslateListener
import com.ntt.benew.dictionary.listener.IViewCallback
import com.ntt.benew.dictionary.listener.OnTTSListener
import com.ntt.benew.dictionary.listener.TxtOnClickListener
import com.ntt.benew.dictionary.model.AnalysisModel
import com.ntt.benew.dictionary.utils.StringUtil
import com.ntt.benew.dictionary.utils.XFUtils
import com.ntt.benew.dictionary.utils.setGradientDrawable
import com.ntt.core.nlogger.NLogger

/**
 * Created by Android Studio.
 * User: tw
 * Date: 2023/10/31
 * Time: 16:30
 * 查句分析
 */
class DictSplitWordView(context: Context) : BaseView(context), IClickPlayerListener {

    private val TAG = javaClass.simpleName

    private var mBinding = DictSplitWordViewBinding.inflate(LayoutInflater.from(context), this)

    private var mLangType: String = LangType.EN

    var mContent: String? = null

    /**
     * GPT 分析后的数据实体
     */
    private var mStructureEntity: StructureEntity? = null

    /**
     * 句子语法分析模式
     */
    private var isSentenceParse: Boolean = false

    fun startTranslate(sentence: String) {
        initModel()
        initClick()
        initView()
        updateState()
        mContent = sentence
        mBinding.enLayout.setTxt(sentence)
        mLangType = if (StringUtil.isPureChinese(sentence)) {
            LangType.CN
        } else {
            LangType.EN
        }
        XFUtils.queryTranslate(sentence, mLangType, object : ITranslateListener {
            override fun refreshContentView(dst: String?, sentences: String?) {
                NLogger.d(TAG, "dst-> $dst , sentence: $sentences")
                mContent = sentence
                mBinding.enLayout.setTxt(sentences ?: "")
                mBinding.cnLayout.setTxt(dst ?: "")
            }

            override fun showErrorView() {
                NLogger.d(TAG)
            }

        })
    }

    private fun initModel() {
        mModel = AnalysisModel()
    }

    private fun initView() {
        val dp20 = SizeUtils.dp2px(20f).toFloat()
        mBinding.bgView.setGradientDrawable(
            R.color.ntt_FBF9E2,
            floatArrayOf(dp20, dp20, dp20, dp20, 0f, 0f, 0f, 0f)
        )
    }

    private fun initClick() {
        EvalManager.registerEvalListener(object : IEvalListener {
            override fun onClickPre() {

            }

            override fun onClickNext() {

            }

            override fun onClose(auto: Boolean) {

            }

            override fun onEvalResult(
                score: Double,
                text: SpannableStringBuilder?,
                result: String?,
                evalEntity: EvalEntity?
            ) {

            }

            override fun onRecordFile(filePath: String?) {

            }

            override fun onDismiss() {

            }

            override fun onShow() {

            }

            override fun onSoundEffect(enable: Boolean, sessionId: Int) {

            }

            override fun onReleaseSoundEffect(sessionId: Int) {

            }

        })
        mBinding.enLayout.mOnClickPlayListener = this
        mBinding.cnLayout.mOnClickPlayListener = this

        mBinding.gpt.setOnClickListener {
//            mICallback?.dismiss()
            mContent?.let { it1 ->
                mModel?.postAnalysisSentenceStructure(it1, object : IAnalysisListener {
                    override fun onSuccess(data: String?) {
                        data?.let {
                            val baseEntity = GsonUtils.fromJson<BaseEntity<StructureEntity>>(
                                it,
                                object : TypeToken<BaseEntity<StructureEntity>>() {}.type
                            )
                            if (baseEntity.code == 200) {
                                baseEntity.data?.let { structure ->
                                    mStructureEntity = structure
                                    mBinding.enLayout.mTxtOnClickListener = onTxtOnClickListener
                                    mBinding.enLayout.setData(
                                        structure.words,
                                        structure.chunking,
                                        mContent ?: ""
                                    )
                                    updateState()
                                    getTTS(structure.original ?: "")
                                }
                            } else {
                                ToastUtils.showShort("请求出错！code: ${baseEntity.data} , e->${baseEntity.message}")
                            }
                        }
                        NLogger.d("GPT返回结果：$data")
                    }

                })
            }
        }
        mBinding.ivClose.setOnClickListener {
            NttPlayCtrl.stop()
            clear()
            mICallback?.dismiss(this)
        }

        mBinding.ivParse.setOnClickListener {
            setSentenceParseState()
        }

    }

    private val onTxtOnClickListener = object : TxtOnClickListener {
        override fun onTxtClick(word: String, chunkingEntity: ChunkingEntity) {
            NLogger.d("点击了 $word")
            if (isSentenceParse) {
                updateCnMessage(chunkingEntity.breakdown)
                getTTS(chunkingEntity.text + chunkingEntity.breakdown)
            } else {
                NttDictionaryManager.startAnalyseWord(word)
            }

        }
    }

    private fun updateState() {
        if (mStructureEntity == null) {
            mBinding.gpt.visibility = View.VISIBLE
            mBinding.groupParse.visibility = View.GONE
        } else {
            mBinding.gpt.visibility = View.INVISIBLE
            mBinding.groupParse.visibility = View.VISIBLE
        }
    }

    /**
     * 点击语块分析 更新状态
     */
    private fun setSentenceParseState() {
        if (mStructureEntity == null) {
            return
        }
        mBinding.gpt.visibility = View.GONE
        mBinding.groupParse.visibility = View.GONE
        isSentenceParse = true
        mStructureEntity!!.chunking?.let {
            mBinding.enLayout.hideHorn()
            mBinding.cnLayout.hideHorn()
            updateCnMessage(it[0].breakdown)
            getTTS(it[0].text + it[0].breakdown)
        }
    }

    /**
     * 更新中文 描述 翻译
     */
    private fun updateCnMessage(content: String?) {
        mBinding.cnLayout.setTxt(content ?: "")
    }

    /**
     * 句子后面的喇叭点击回调
     */
    override fun play(original: String) {
        if (original.isBlank()) {
            return
        }
        getTTS(original)
    }

    private fun getTTS(original: String) {
        if (original.isBlank()){
            return
        }
        BenewApiManager.requestTTS(original, object : OnTTSListener {
            override fun onSuccess(tts: String) {
                playTTS(tts)
            }
        })
    }

    /**
     * 播放tts
     */
    private fun playTTS(url: String) {
        NttPlayCtrl.playAudio(
            AudioItem(url)
        )
    }

    private fun clear(){
        isSentenceParse = false
        mStructureEntity = null
        mContent = null
    }

}